package com.elysia.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.elysia.gulimall.product.service.CategoryBrandRelationService;
import com.elysia.gulimall.product.vo.Level2CategoryVo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.elysia.common.utils.PageUtils;
import com.elysia.common.utils.Query;

import com.elysia.gulimall.product.dao.CategoryDao;
import com.elysia.gulimall.product.entity.CategoryEntity;
import com.elysia.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redisson;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //1.查出所有分类
        List<CategoryEntity> entities=baseMapper.selectList(null);
        //2.组成树形结构
        //2.一级分类
        List<CategoryEntity> level1Menus=entities.stream().filter(categoryEntity ->
                categoryEntity.getParentCid()==0
        ).map(menu->{
            menu.setChildren(getChildren(menu,entities));
            return menu;
        }).sorted((menu1,menu2)->
                menu1.getSort()-menu2.getSort()
        ).collect(Collectors.toList());

        return level1Menus;
    }

    @Override
    public void removeMenusByIds(List<Long> list) {
        //TODO 检查菜单是否被其他地方引用
        //逻辑删除
        baseMapper.deleteBatchIds(list);
    }

    /**
     * 获取所属分类路径
     * @param catelogId
     * @return
     */
    @Override
    public Long[] getCategoryPathById(Long catelogId) {
        List<Long> categoryIds=new ArrayList<>();
        categoryIds.add(catelogId);
        while((catelogId=this.getById(catelogId).getParentCid())!=0){
            categoryIds.add(catelogId);
        }
        Collections.reverse(categoryIds);
        return categoryIds.toArray(new Long[categoryIds.size()]);
    }

    /**
     * 级联更新
     * @param category
     */
    @Transactional
    @CacheEvict(cacheNames = "category",allEntries = true)
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());
    }

    /**
     * 从缓存中获取一级分类，加读写锁
     * @return
     */
    @Cacheable(cacheNames = "category",key = "#root.methodName",sync = true)
    @Override
    public List<CategoryEntity> getLevel1Category() {
        System.out.println("getLevel1Category...");
        return this.list(new QueryWrapper<CategoryEntity>().eq("cat_level",1).eq("show_status",1));
    }

    /**
     * 使用SpringCache 缓存 二三级分类，并加上本地锁
     * @return
     */
    @Cacheable(cacheNames = "category",key = "'getLevel2AndLevel3Category'",sync = true)
    @Override
    @Transactional
    public Map<String, List<Level2CategoryVo>> getLevel2AndLevel3CategoryWithSpringCache(){

        Map<String, List<Level2CategoryVo>> res = null;

        System.out.println("查询数据库...");
        //缓存中无数据，再查询数据库
        List<CategoryEntity> selectList = this.baseMapper.selectList(null);

        //一级分类
        List<CategoryEntity> level1 = this.getByParentCid(selectList,0L);

        Map<String, List<Level2CategoryVo>> categoryMap = level1.stream().collect(Collectors.toMap(k -> k.getCatId().toString(),v ->{
            //查询该一级分类下的二级分类
            List<CategoryEntity> level2List = getByParentCid(selectList,v.getCatId());

            List<Level2CategoryVo> level2CategoryVos = null;
            if (level2List != null){
                level2CategoryVos = level2List.stream().map(level2 -> {
                    //查询 二级分类 下的 三级分类
                    List<CategoryEntity> level3List = getByParentCid(selectList,level2.getCatId());

                    List<Level2CategoryVo.Level3Category> collect = null;
                    if (level3List != null) {
                        collect = level3List.stream().map(level3 -> {
                            Level2CategoryVo.Level3Category level3Category = new Level2CategoryVo.Level3Category(level2.getCatId(), level3.getCatId(), level3.getName());
                            return level3Category;
                        }).collect(Collectors.toList());
                    }
                    Level2CategoryVo level2CategoryVo = new Level2CategoryVo(v.getCatId(), collect, level2.getCatId(), level2.getName());
                    return level2CategoryVo;
                }).collect(Collectors.toList());
            }
            return level2CategoryVos;
        }));

        return categoryMap;
    }

    /**
     * 使用redis手动读写缓存，并基于redisson实现分布式锁
     * @return
     */
    @Override
    public Map<String, List<Level2CategoryVo>> getLevel2AndLevel3Category() {
        //1.先从缓存中获取 catalogJson
        ValueOperations<String,String> valueOperations = redisTemplate.opsForValue();
        String catalogJson = valueOperations.get("catalogJson");
        Map<String, List<Level2CategoryVo>> res = null;
        if(StringUtils.isEmpty(catalogJson)){
            //缓存中无对应数据，查询数据库
            res = getCatalogJsonFromDBWithRedissonLock();
        }else{
            res = JSON.parseObject(catalogJson,new TypeReference<Map<String, List<Level2CategoryVo>> >(){});
        }
        return res;
    }

    /**
     * 获取 Redisson 分布式锁，查询数据库
     * @return
     */
    private Map<String, List<Level2CategoryVo>> getCatalogJsonFromDBWithRedissonLock(){
        Map<String, List<Level2CategoryVo>> res = null;
        RLock lock = redisson.getLock("CatalogJson-Lock");
        lock.lock();
        //成功获取到锁
        try {
            res = getCatalogJsonFromDB();
        }finally {
            lock.unlock();
        }
        return res;
    }

    /**
     * 获取setNX分布式锁，查询数据库
     * @return
     */
    private Map<String, List<Level2CategoryVo>> getCatalogJsonFromDBWithLock(){
        ValueOperations<String,String> valueOperations = redisTemplate.opsForValue();
        String uuid = UUID.randomUUID().toString();
        //必须设置 过期时间，避免死锁，set和过期 必须是原子的
        Boolean lock = valueOperations.setIfAbsent("lock",uuid,300,TimeUnit.SECONDS);
        if (lock){
            System.out.println("成功获取lock...");
            //成功获取到锁
            Map<String, List<Level2CategoryVo>> res = null;

            try {
                res = getCatalogJsonFromDB();
            }finally {
                String script = "if redis.call('get',KEYS[1]) == ARGV[1] " +
                        "then return redis.call('del',KEYS[1]) " +
                        "else return 0 " +
                        "end";
                redisTemplate.execute(new DefaultRedisScript<Long>(script,Long.class),Arrays.asList("lock"),uuid);
                System.out.println("释放lock");
            }

            return res;
        }else{
            System.out.println("自旋等待lock...");
            //没有获取到锁，自旋等待
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return getCatalogJsonFromDBWithLock();
        }
    }

    /**
     * 从数据库中 获取 2 3 级 分类
     * @return
     */
    private Map<String, List<Level2CategoryVo>> getCatalogJsonFromDB(){

        //获得锁后，再次确认，有无缓存
        ValueOperations<String,String> valueOperations = redisTemplate.opsForValue();
        String catalogJson = valueOperations.get("catalogJson");
        Map<String, List<Level2CategoryVo>> res = null;
        if(!StringUtils.isEmpty(catalogJson)) {
            //缓存有数据
            res = JSON.parseObject(catalogJson,new TypeReference<Map<String, List<Level2CategoryVo>> >(){});
            return res;
        }

        System.out.println("查询数据库...");
        //缓存中无数据，再查询数据库
        List<CategoryEntity> selectList = this.baseMapper.selectList(null);

        //一级分类
        List<CategoryEntity> level1 = this.getByParentCid(selectList,0L);

        Map<String, List<Level2CategoryVo>> categoryMap = level1.stream().collect(Collectors.toMap(k -> k.getCatId().toString(),v ->{
            //查询该一级分类下的二级分类
            List<CategoryEntity> level2List = getByParentCid(selectList,v.getCatId());

            List<Level2CategoryVo> level2CategoryVos = null;
            if (level2List != null){
                level2CategoryVos = level2List.stream().map(level2 -> {
                    //查询 二级分类 下的 三级分类
                    List<CategoryEntity> level3List = getByParentCid(selectList,level2.getCatId());

                    List<Level2CategoryVo.Level3Category> collect = null;
                    if (level3List != null) {
                        collect = level3List.stream().map(level3 -> {
                            Level2CategoryVo.Level3Category level3Category = new Level2CategoryVo.Level3Category(level2.getCatId(), level3.getCatId(), level3.getName());
                            return level3Category;
                        }).collect(Collectors.toList());
                    }
                    Level2CategoryVo level2CategoryVo = new Level2CategoryVo(v.getCatId(), collect, level2.getCatId(), level2.getName());
                    return level2CategoryVo;
                }).collect(Collectors.toList());
            }
            return level2CategoryVos;
        }));

        //查询后 加入缓存
        valueOperations.set("catalogJson", JSON.toJSONString(categoryMap),1, TimeUnit.DAYS);
        return categoryMap;
    }

    /**
     * 获取某分类下的所有子分类
     * @param selectList
     * @param parentCid
     * @return
     */
    private List<CategoryEntity> getByParentCid(List<CategoryEntity> selectList,Long parentCid) {
        return selectList.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid().equals(parentCid);
        } ).collect(Collectors.toList());
    }

    /**
     * 、递归查询 分类树
     * @param root
     * @param all
     * @return
     */
    private List<CategoryEntity> getChildren(CategoryEntity root,List<CategoryEntity> all){
        List<CategoryEntity> children=all.stream().filter(categoryEntity ->
                categoryEntity.getParentCid().equals(root.getCatId())
        ).map(menu->{
            menu.setChildren(getChildren(menu,all));
            return menu;
        }).sorted((menu1,menu2)->
                (menu1.getSort()==null?0:menu1.getSort())-(menu2.getSort()==null?0: menu2.getSort())
        ).collect(Collectors.toList());
        return children;
    }

}